<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { message } from 'ant-design-vue';

// 接口定义
interface Product {
  id: string;
  name: string;
  specification: string;
  unit: string;
  unitPrice: number;
  discountEligible: boolean;
  category: string;
  quantity: number;
}

interface Props {
  visible: boolean;
}

interface Emits {
  (e: 'update:visible',value: boolean): void;
  (e: 'select',products: Product[]): void
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const searchKeyword = ref('');
const selectedCategory = ref('');
const selectedProducts = ref<string[]>([]);
const selectedProductList = ref<Product[]>([]);

// 模拟商品数据
const products = ref<Product[]>([
  {
    id: '1',
    name: '路斯牛肉粒',
    specification: '500g',
    unit: '袋',
    unitPrice: 50,
    discountEligible: false,
    category: 'food',
    quantity: 1,
  },
  {
    id: '2',
    name: '皇家狗粮',
    specification: '2kg',
    unit: '袋',
    unitPrice: 120,
    discountEligible: true,
    category: 'food',
    quantity: 1,
  },
  {
    id: '3',
    name: '宠物维生素',
    specification: '60片',
    unit: '瓶',
    unitPrice: 80,
    discountEligible: true,
    category: 'medicine',
    quantity: 1,
  },
  {
    id: '4',
    name: '宠物玩具球',
    specification: '直径8cm',
    unit: '个',
    unitPrice: 25,
    discountEligible: true,
    category: 'toy',
    quantity: 1,
  },
  {
    id: '5',
    name: '宠物洗发水',
    specification: '500ml',
    unit: '瓶',
    unitPrice: 60,
    discountEligible: true,
    category: 'care',
    quantity: 1,
  },
  {
    id: '6',
    name: '宠物驱虫药',
    specification: '3片装',
    unit: '盒',
    unitPrice: 45,
    discountEligible: false,
    category: 'medicine',
    quantity: 1,
  },
]);

// 计算属性
const filteredProducts = computed(() => {
  let filtered = products.value;

  if (selectedCategory.value) {
    filtered = filtered.filter(
      (product) => product.category === selectedCategory.value,
    );
  }

  if (searchKeyword.value) {
    filtered = filtered.filter(
      (product) =>
        product.name.includes(searchKeyword.value) ||
        product.specification.includes(searchKeyword.value),
    );
  }

  return filtered;
});

// 方法
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
};

const handleCategoryChange = () => {
  // 分类筛选逻辑已在计算属性中处理
};

const toggleProductSelection = (product: Product) => {
  const index = selectedProducts.value.indexOf(product.id);
  if (index === -1) {
    selectedProducts.value.push(product.id);
    selectedProductList.value.push({ ...product });
  } else {
    selectedProducts.value.splice(index, 1);
    selectedProductList.value = selectedProductList.value.filter(
      (p) => p.id !== product.id,
    );
  }
};

const handleProductCheckboxChange = (product: Product, checked: boolean) => {
  if (checked) {
    if (!selectedProducts.value.includes(product.id)) {
      selectedProducts.value.push(product.id);
      selectedProductList.value.push({ ...product });
    }
  } else {
    const index = selectedProducts.value.indexOf(product.id);
    if (index !== -1) {
      selectedProducts.value.splice(index, 1);
      selectedProductList.value = selectedProductList.value.filter(
        (p) => p.id !== product.id,
      );
    }
  }
};

const removeSelectedProduct = (productId: string) => {
  selectedProducts.value = selectedProducts.value.filter(
    (id) => id !== productId,
  );
  selectedProductList.value = selectedProductList.value.filter(
    (p) => p.id !== productId,
  );
};

const clearAll = () => {
  selectedProducts.value = [];
  selectedProductList.value = [];
};

const handleCancel = () => {
  emit('update:visible', false);
  resetModal();
};

const handleConfirm = () => {
  if (selectedProductList.value.length === 0) {
    message.warning('请至少选择一个商品');
    return;
  }

  emit('select', selectedProductList.value);
  emit('update:visible', false);
  resetModal();
};

const resetModal = () => {
  searchKeyword.value = '';
  selectedCategory.value = '';
  selectedProducts.value = [];
  selectedProductList.value = [];
};

// 监听模态框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (!visible) {
      resetModal();
    }
  },
);
</script>

<template>
  <a-modal
    :visible="visible"
    title="选择商品"
    width="800px"
    @cancel="handleCancel"
    :footer="null"
  >
    <div class="product-modal">
      <!-- 搜索和筛选 -->
      <div class="search-section">
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索商品"
          style="width: 300px"
          @search="handleSearch"
        />
        <a-select
          v-model:value="selectedCategory"
          style="width: 150px"
          placeholder="选择分类"
          @change="handleCategoryChange"
        >
          <a-select-option value="">全部分类</a-select-option>
          <a-select-option value="food">宠物食品</a-select-option>
          <a-select-option value="medicine">宠物药品</a-select-option>
          <a-select-option value="toy">宠物玩具</a-select-option>
          <a-select-option value="care">护理用品</a-select-option>
        </a-select>
      </div>

      <!-- 商品列表 -->
      <div class="product-list">
        <div class="product-grid">
          <div
            v-for="product in filteredProducts"
            :key="product.id"
            class="product-card"
            :class="{ selected: selectedProducts.includes(product.id) }"
            @click="toggleProductSelection(product)"
          >
            <div class="product-checkbox">
              <a-checkbox
                :checked="selectedProducts.includes(product.id)"
                @change="
                  (e) => handleProductCheckboxChange(product, e.target.checked)
                "
              />
            </div>
            <div class="product-info">
              <div class="product-name">{{ product.name }}</div>
              <div class="product-spec">{{ product.specification }}</div>
              <div class="product-unit">{{ product.unit }}</div>
              <div class="product-price">¥{{ product.unitPrice }}</div>
              <div class="product-discount">
                <a-tag :color="product.discountEligible ? 'green' : 'default'">
                  {{ product.discountEligible ? '参与打折' : '不参与打折' }}
                </a-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 已选择商品 -->
      <div v-if="selectedProductList.length > 0" class="selected-products">
        <div class="selected-header">
          <h4>已选择商品</h4>
          <a-button type="link" size="small" @click="clearAll">
            清空全部
          </a-button>
        </div>
        <div class="selected-list">
          <div
            v-for="product in selectedProductList"
            :key="product.id"
            class="selected-item"
          >
            <div class="selected-info">
              <div class="selected-name">{{ product.name }}</div>
              <div class="selected-spec">{{ product.specification }}</div>
            </div>
            <div class="selected-quantity">
              <a-input-number
                v-model:value="product.quantity"
                :min="1"
                size="small"
                style="width: 80px"
              />
            </div>
            <div class="selected-price">
              ¥{{ (product.unitPrice * product.quantity).toFixed(2) }}
            </div>
            <div class="selected-action">
              <a-button
                type="text"
                danger
                size="small"
                @click="removeSelectedProduct(product.id)"
              >
                ×
              </a-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="modal-actions">
        <a-button @click="handleCancel">取消</a-button>
        <a-button type="primary" @click="handleConfirm">
          确认选择 ({{ selectedProductList.length }})
        </a-button>
      </div>
    </div>
  </a-modal>
</template>

<style scoped>
.product-modal {
  display: flex;
  flex-direction: column;
  height: 600px;
}

.search-section {
  display: flex;
  gap: 16px;
  padding-bottom: 16px;
  margin-bottom: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.product-list {
  flex: 1;
  margin-bottom: 16px;
  overflow-y: auto;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 16px;
}

.product-card {
  display: flex;
  gap: 12px;
  padding: 12px;
  cursor: pointer;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  transition: all 0.3s;
}

.product-card:hover {
  background: #f0f8ff;
  border-color: #1890ff;
}

.product-card.selected {
  background: #e6f7ff;
  border-color: #1890ff;
}

.product-checkbox {
  display: flex;
  align-items: center;
}

.product-info {
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: 4px;
}

.product-name {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.product-spec {
  font-size: 12px;
  color: #666;
}

.product-unit {
  font-size: 12px;
  color: #999;
}

.product-price {
  font-size: 14px;
  font-weight: bold;
  color: #ff4d4f;
}

.product-discount {
  margin-top: 4px;
}

.selected-products {
  padding-top: 16px;
  margin-bottom: 16px;
  border-top: 1px solid #e8e8e8;
}

.selected-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.selected-header h4 {
  margin: 0;
  color: #333;
}

.selected-list {
  max-height: 200px;
  overflow-y: auto;
}

.selected-item {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 8px;
  margin-bottom: 8px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.selected-info {
  flex: 1;
}

.selected-name {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.selected-spec {
  font-size: 12px;
  color: #666;
}

.selected-quantity {
  width: 80px;
}

.selected-price {
  width: 80px;
  font-weight: bold;
  color: #ff4d4f;
  text-align: right;
}

.selected-action {
  width: 40px;
  text-align: center;
}

.modal-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}
</style>
